<template>
  <div class="app-container">
    <!--搜索表单-->
    <el-form :inline="true" :model="searchAnnouncement" class="demo-form-inline">
      <el-form-item label="标题">
        <el-input
          v-model="searchAnnouncement.title"
          placeholder="请输入公告标题"
        ></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchAnnouncement.status" placeholder="请选择状态">
          <el-option label="全部" value=""></el-option>
          <el-option label="草稿" value="0"></el-option>
          <el-option label="已发布" value="1"></el-option>
          <el-option label="已撤回" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="createTime"
          clearable
          value-format="yyyy-MM-dd"
          type="daterange"
          placeholder="选择日期"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 400px; margin-left: 20px"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button type="info" @click="clear">清空</el-button>
      </el-form-item>
    </el-form>

    <div class="operation-container" v-if="isAdmin">
      <el-button type="danger" @click="handleBatchDelete" :disabled="multipleSelection.length === 0">批量删除</el-button>
    </div>

    <br>
    <!--公告列表-->
    <el-table
      v-if="tableData.length > 0"
      :data="tableData"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column
        v-if="isAdmin"
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column
        type="index"
        label="序号"
        width="80"
        align="center">
      </el-table-column>
      <el-table-column
        prop="title"
        label="标题">
        <template slot-scope="scope">
          <span class="announcement-title">{{ scope.row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="author"
        label="作者"
        width="120"
        align="center">
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="发布时间"
        width="180"
        align="center">
        <template slot-scope="scope">
          {{ scope.row.createTime ? scope.row.createTime.replace('T', ' ') : '' }}
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
        width="100"
        align="center">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        :width="isAdmin ? '250' : '120'"
        align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="viewDetail(scope.row)">查看详情</el-button>
          <template v-if="isAdmin">
            <el-button 
              v-if="scope.row.status === 0" 
              type="warning" 
              size="small" 
              @click="handleEdit(scope.row.id)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <div v-if="tableData.length === 0" class="empty-data">
      <i class="el-icon-document"></i>
      <p>暂无公告</p>
    </div>

    <!--公告详情对话框-->
    <el-dialog title="公告详情" :visible.sync="dialogVisible" width="70%" top="5vh">
      <h2 class="detail-title">{{ currentAnnouncement.title }}</h2>
      <div class="detail-info">
        <span>作者: {{ currentAnnouncement.author }}</span>
        <span>状态: {{ getStatusText(currentAnnouncement.status) }}</span>
        <span>发布时间: {{ currentAnnouncement.createTime ? currentAnnouncement.createTime.replace('T', ' ') : '' }}</span>
      </div>
      <div class="detail-content" v-html="currentAnnouncement.content">
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button 
          v-if="isAdmin && currentAnnouncement.status === 0" 
          type="warning" 
          @click="handleEdit(currentAnnouncement.id)">编辑</el-button>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>

    <!--分页工具条-->
    <el-pagination
      :background="background"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import { page, deleteById, batchDelete } from "@/api/announcement.js";
import { mapGetters } from 'vuex';

export default {
  data() {
    return {
      background: true,
      // 每页显示的条数
      pageSize: 10,
      // 总记录数
      totalCount: 0,
      // 当前页码
      currentPage: 1,
      // 公告详情对话框是否展示
      dialogVisible: false,
      // 搜索模型数据
      searchAnnouncement: {
        title: "",
        status: ""
      },
      // 当前查看的公告
      currentAnnouncement: {},
      
      beginTime: "",
      endTime: "",
      createTime: "",

      // 表格数据
      tableData: [],
      
      // 多选
      multipleSelection: []
    };
  },

  computed: {
    ...mapGetters([
      'isAdmin',
      'isUser',
      'roles'
    ])
  },

  watch: {
    createTime(val) {
      if (val && val.length >= 2) {
        this.beginTime = val[0];
        this.endTime = val[1];
      } else {
        this.beginTime = "";
        this.endTime = "";
      }
    }
  },

  mounted() {
    console.log('公告查看页面 - 当前用户角色:', this.roles)
    console.log('公告查看页面 - 是否管理员:', this.isAdmin)
    console.log('公告查看页面 - 是否普通用户:', this.isUser)
    this.page(); // 当页面加载完成后，发送异步请求，获取数据
  },

  methods: {
    // 查询分页数据
    page() {
      // 如果是普通用户，只能查看已发布的公告
      const status = this.isUser && !this.isAdmin ? "1" : this.searchAnnouncement.status;
      
      page(
        this.searchAnnouncement.title,
        status,
        this.beginTime,
        this.endTime,
        this.currentPage,
        this.pageSize
      ).then((res) => {
        this.totalCount = res.data.data.total;
        this.tableData = res.data.data.rows;
      });
    },

    // 获取状态文本
    getStatusText(status) {
      switch(parseInt(status)) {
        case 0: return '草稿';
        case 1: return '已发布';
        case 2: return '已撤回';
        default: return '未知';
      }
    },

    // 获取状态对应的标签类型
    getStatusType(status) {
      switch(parseInt(status)) {
        case 0: return 'info';
        case 1: return 'success';
        case 2: return 'warning';
        default: return '';
      }
    },

    // 编辑公告（跳转到发布页面）
    handleEdit(id) {
      if (!this.isAdmin) {
        this.$message.warning('您没有编辑权限');
        return;
      }
      this.$router.push({ path: '/announcement/publish', query: { id: id }});
    },

    // 查询方法
    onSubmit() {
      this.currentPage = 1;
      this.page();
    },

    clear() {
      this.searchAnnouncement = { 
        title: "",
        status: ""
      };
      this.beginTime = "";
      this.endTime = "";
      this.createTime = "";
      this.page();
    },
    
    // 获取预览内容（去除HTML标签，只保留文本）
    getPreviewContent(html) {
      if (!html) return '';
      
      // 创建临时元素来解析HTML
      const tempDiv = document.createElement('div');
      tempDiv.innerHTML = html;
      
      // 获取纯文本内容
      let text = tempDiv.textContent || tempDiv.innerText || '';
      
      // 截取前100个字符
      if (text.length > 100) {
        text = text.substring(0, 100) + '...';
      }
      
      return text;
    },
    
    // 查看公告详情
    viewDetail(announcement) {
      this.currentAnnouncement = announcement;
      this.dialogVisible = true;
    },

    // 处理表格多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    // 删除单个公告
    handleDelete(id) {
      if (!this.isAdmin) {
        this.$message.warning('您没有删除权限');
        return;
      }
      
      this.$confirm('此操作将永久删除该公告, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteById(id).then(res => {
          if (res.data.code === '1' || res.data.code === 1) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.page(); // 重新加载数据
          } else {
            this.$message.error(res.data.msg);
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 批量删除公告
    handleBatchDelete() {
      if (!this.isAdmin) {
        this.$message.warning('您没有删除权限');
        return;
      }
      
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请至少选择一条记录');
        return;
      }

      this.$confirm(`确认批量删除选中的 ${this.multipleSelection.length} 条公告记录吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = this.multipleSelection.map(item => item.id).join(',');
        batchDelete(ids).then(res => {
          if (res.data.code === '1' || res.data.code === 1) {
            this.$message({
              type: 'success',
              message: '批量删除成功!'
            });
            this.page(); // 重新加载数据
          } else {
            this.$message.error(res.data.msg);
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 分页
    handleSizeChange(val) {
      // 重新设置每页显示的条数
      this.pageSize = val;
      this.page();
    },

    handleCurrentChange(val) {
      // 重新设置当前页码
      this.currentPage = val
      this.page()
    }
  }
}
</script>

<style scoped>
.operation-container {
  margin-bottom: 15px;
}

.announcement-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-bottom: 30px;
}

.announcement-card {
  width: 100%;
  transition: all 0.3s;
}

.announcement-card:hover {
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.announcement-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.announcement-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  color: #909399;
  font-size: 14px;
}

.announcement-content {
  color: #606266;
  line-height: 1.6;
  white-space: pre-line;
}

.detail-title {
  text-align: center;
  margin-bottom: 20px;
  font-size: 22px;
  color: #303133;
}

.detail-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  color: #909399;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 15px;
}

.detail-content {
  line-height: 1.8;
  padding: 20px;
  min-height: 300px;
  color: #303133;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.empty-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
  color: #909399;
}

.empty-data i {
  font-size: 50px;
  margin-bottom: 20px;
}

.el-pagination {
  text-align: center;
  margin-top: 20px;
}
</style> 
